import React, { Component } from "react"
import Ionicon from "react-ionicons"

export class Carousel extends Component {
  state = {
    listWidth: 0,
    carouselWidth: 0,
    activeIndex: 0
  }

  componentDidMount() {
    // 获取最外层 div 的宽度和计算列表容器的宽度
    const { children } = this.props
    const carouselWidth = this.carousel.offsetWidth
    const listWidth = carouselWidth * (children.length && children.length)
    this.setState({
      listWidth,
      carouselWidth
    })
  }

  handleDotClick = (event, index) => {
    this.setState({
      activeIndex: index
    })
  }

  handleLeftClick = event => {
    let { activeIndex } = this.state
    let newIndex = activeIndex - 1
    if(newIndex < 0) newIndex = this.props.children.length - 1
    this.setState({
      activeIndex: newIndex
    })
  }

  handleRightClick = (event) => {
    const { activeIndex } = this.state
    let newIndex = activeIndex + 1
    if(newIndex >= this.props.children.length) newIndex = 0
    this.setState({
      activeIndex: newIndex
    })
  }

  render() {
    const { children } = this.props
    const { listWidth, carouselWidth, activeIndex } = this.state
    const translateX = activeIndex * (- this.state.carouselWidth)
    // 改变 list 的 transform 从而产生动画
    const transformValue = `translate3d(${translateX}px,0,0)`
    return (
      <div ref={ref => (this.carousel = ref)} className="zoo-carousel">
        <div
          ref={ref => (this.list = ref)}
          className="list"
          style={{ width: listWidth, transform: transformValue}}
        >
          {React.Children.map(children, (child, index) => {
            return (
              <div className="item" style={{ width: carouselWidth }}>
                {child}
              </div>
            )
          })}
        </div>
        <div className="dots">
          {React.Children.map(children, (child, index) => {
            const dotClassName = activeIndex === index ? "active dot" : "dot"
            return (
              <span
                onClick={event => this.handleDotClick(event, index)}
                className={dotClassName}
              />
            )
          })}
        </div>
        <div onClick={this.handleLeftClick} className="arrow arrow-left">
          <Ionicon fontSize="50px" color="#282b33" icon="ios-arrow-forward" />
        </div>
        <div onClick={this.handleRightClick} className="arrow arrow-right">
          <Ionicon fontSize="50px" color="#282b33" icon="ios-arrow-forward" />
        </div>
      </div>
    )
  }
}

export const CarouselItem = ({ children }) => (
  <React.Fragment>{children}</React.Fragment>
)

export default Carousel
